<?php

namespace app\data\controller;

use app\data\model\LiveAppList;
use app\data\model\LiveIndustryList;
use app\data\model\LiveProxyList;
use app\data\model\LiveThaliList;
use app\data\model\LiveUserList;
use app\data\model\LiveUserLoginlog;
use Ip2Region;
use think\admin\Controller;

/**
 * 用户管理
 * Class UserListController
 * @package app\data\controller
 */
class UserListController extends Controller
{
    /**
     * 查询
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function index(){
        $this->title = '用户管理';
        $this->type = $this->request->get('type', 'index');
        $this->proxys = LiveProxyList::mk()->field('id,user_nickname,user_account')->select()->toArray();
        $this->apps = LiveAppList::mk()->field('app_id,app_name')->select()->toArray();
        $this->thalis = LiveThaliList::mk()->field('thali_id,thali_name')->select()->toArray();
        $this->industrys = LiveIndustryList::mk()->field('industry_id,industry_name')->select()->toArray();
        $this->lastLoginTimes = LiveUserLoginlog::mk()->field('user_id, MAX(login_time) AS latest_login_time')->group('user_id')->select()->toArray();

        $query = LiveUserList::mQuery();
        //'youxiao'=>'有效用户','guoqi'=>'过期用户','santian'=>'近三天登录'
        $date = date('Y-m-d', strtotime("-3days"));

        if ($this->type === 'index') $query->where(['deleted' => 0]);
        elseif ($this->type === 'youxiao') $query->where(['deleted' => 0])->whereRaw('thali_endtime >= NOW()');
        elseif ($this->type === 'guoqi') $query->where(['deleted' => 0])->whereRaw('thali_endtime < NOW()');
        elseif ($this->type === 'santian') $query->where(['deleted' => 0])->whereBetween('login_time', [$date . ' 00:00:00', date('Y-m-d') . ' 23:59:59']);
        else $this->error("无法加载 {$this->type} 数据列表！");

        $query->like('user_nickname');
        $query->equal('pid,user_state,industry_id,app_id');
        $query->dateBetween('create_time');
        $query->order('create_time desc')->page();
    }
    /**
     * 列表数据处理
     * @auth true
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(array &$data)
    {
        $region = new Ip2Region();
        foreach ($data as &$vo) {
            $isp = $region->btreeSearch($vo['login_ip']);
            $vo['login_address'] = str_replace(['内网IP', '0', '|'], '', $isp['region'] ?? '') ?: '-';
        }
    }


    /**
     * 编辑
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function edit()
    {
        LiveUserList::mForm('edit', 'id');
    }

    /**
     * 编辑表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _edit_form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            $this->apps = LiveAppList::mk()->field('app_id,app_name')->where(['deleted' => 0])->select()->toArray();
            $this->industrys = LiveIndustryList::mk()->field('industry_id,industry_name')->where(['deleted' => 0])->select()->toArray();
        }
        if ($this->request->isPost()) {
            if (strpos($data['user_nickname'], " ") !== false)  $this->error('昵称含有空格！');
            if (strpos($data['user_password'], " ") !== false)  $this->error('密码含有空格！');
            if(empty($data['industry_id'])) $this->error('请选择行业！');
            if(empty($data['app_id'])) $this->error('请选择APP应用！');
            //更新内容
            LiveUserList::mk()->where(['id' => $data['id']])->update([
                'user_nickname'     => $data['user_nickname'],
                'user_password'     => $data['user_password'],
                'industry_id'       => $data['industry_id'],
                'app_id'            => $data['app_id'],
            ]);
            $this->success('编辑成功！');
        }
    }

    /**
     * 设置登录状态
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function userstate()
    {
        LiveUserList::mSave($this->_vali([
            'user_state.in:0,1'  => '状态值范围异常！',
            'user_state.require' => '状态值不能为空！',
        ]), 'id');
    }
}